package leetcode;

/**
 * @author Liangyaoyun
 */
public class leetCode63 {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int line = obstacleGrid.length;
        int row = obstacleGrid[0].length;
        int[][] dp = new int[line][row];
        dp[0][0] = 1;
        if (obstacleGrid[line - 1][row - 1] == 1 || obstacleGrid[0][0] == 1) {
            return 0;
        }
        if (row == 2 && line == 2) {
            if (obstacleGrid[1][0] == 1 && obstacleGrid[0][1] == 1) {
                return 0;
            }
            return obstacleGrid[1][0] == 1 || obstacleGrid[0][1] == 1 ? 1 : 2;
        }
        for (int i = 0; i < line; i++) {
            for (int j = 0; j < row; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else if (i == 0 || j == 0){
                    if (i==0){
                        dp[i][j]=dp[i][j-1];
                    }else if (j==0){
                        dp[i][j]=dp[i-1][j];
                    }
                }
                else {
                    dp[i][j]=dp[i-1][j]+dp[i][j-1];
                }
            }
        }
        return dp[line - 1][row - 1];
    }

    public static void main(String[] args) {
        int[][] obstacleGrid = new int[][]{{0, 0,0}, {0, 1,0},{0,0,0}};
        leetCode63 leetCode63 = new leetCode63();
        System.out.println(leetCode63.uniquePathsWithObstacles(obstacleGrid));
    }
}
